package com.zj.open.wechat.service.processor;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.zj.open.wechat.dao.UserMapper;
import com.zj.open.wechat.dto.event.Events;
import com.zj.open.wechat.dto.event.SubscribeEvent;
import com.zj.open.wechat.model.User;

@Component
public class SubscribeEventProcessor extends MessageProcessor<SubscribeEvent> {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserMapper userMapper;

    @Override
    public void process(SubscribeEvent event) {
        if (Events.subscribe.name().equals(event.getEvent())) {
            User user = userMapper.selectByOpenId(event.getFromUserName());
            if (user == null) {
                user = new User();
                user.setFirstSubscribeTime(new Date(Long.parseLong(event.getCreateTime())));
                user.setOpenid(event.getFromUserName());
                user.setSubscribed(Boolean.TRUE);
                user.setSubscribeTime(new Date(Long.parseLong(event.getCreateTime())));

                if (event.getEventKey() != null) {
                    user.setSceneId(event.getEventKey());// TODO not verified
                }
                userMapper.insertSelective(user);
            } else {
                user.setSubscribed(Boolean.TRUE);
                user.setSubscribeTime(new Date(Long.parseLong(event.getCreateTime())));
                userMapper.updateByPrimaryKeySelective(user);
            }
        } else if (Events.unsubscribe.name().equals(event.getEvent())) {
            User user = userMapper.selectByOpenId(event.getFromUserName());
            user.setSubscribed(Boolean.FALSE);
            user.setUnsubscribeTime(new Date(Long.parseLong(event.getCreateTime())));
            userMapper.updateByPrimaryKeySelective(user);
        }

        logger.info(JSON.toJSONString(event));
    }
}